package indi.kider.server.woniubus.service;

import indi.kider.common.constant.BusStateCons;
import indi.kider.common.constant.RentStateCons;
import indi.kider.common.constant.StatusCons;
import indi.kider.common.model.apabus.*;
import indi.kider.common.model.apartment.Community;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.employee.Employee;
import indi.kider.common.model.employee.Tenant;
import indi.kider.common.model.employee.Waiter;
import indi.kider.server.apabus.mapper.BusMapper;
import indi.kider.server.apabus.mapper.RentMapper;
import indi.kider.server.apartment.mapper.CommunityMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.employee.mapper.TenantMapper;
import indi.kider.server.employee.mapper.WaiterMapper;
import lombok.extern.java.Log;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageResponse;
import pers.vankid.common.utils.page.PageUtil;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@SuppressWarnings("ALL")
@Log
public class BusServiceImpl implements BusService {

    @Autowired
    private BusMapper busMapper;
    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private WaiterMapper witerMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 更新 申请和派单  的warningState状态
     * 1正常 2 超时2小时 3超时4小时 4超时8小时
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public  CommonResponse updateBusWarningState()throws Exception{
        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowStr = format.format(now);

        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(BusStateCons.APPLY);
        arr.add(BusStateCons.ORDER);
        Example example = new Example(Bus.class);
        example.createCriteria().andIn("state",arr);
        List<Bus> list = busMapper.selectByExample(example);
        for(Bus bus : list){
            Integer ws = 1;
            if(bus.getState() == 1){
                ws = getIntByDate(bus.getInsTime(),now);
            }else if(bus.getState() == 2){
                ws = getIntByDate(bus.getWaiterTime(),now);
            }
            bus.setWarningState(ws);
            bus.setRemark("状态更新执行时间:"+nowStr);
            busMapper.updateByPrimaryKeySelective(bus);
        }
        return CommonResponse.buildUpdateSuccessResponse("更新服务状态完成!",null);
    }
    // 1正常 2 超时2小时 3超时4小时 4超时8小时
    private Integer getIntByDate(Date date ,Date now){
        //计算差值，小时数
        long h=(now.getTime()-date.getTime())/(1000*60*60);
        Integer retInt = 1;
        if(h<2){
            retInt = 1;
        }else if(2<=h && h<4){
            retInt = 2;
        }else if(4<=h && h<8){
            retInt = 3;
        }else{
            retInt = 4;
        }
        return retInt;
    }

    /**
     * 查看房间租客列表
     * @param houseId
     * @return
     * @throws Exception
     */
    public  List<Rent> getTenantListByHouseId(Long houseId)throws Exception{
        Rent query = new Rent();
        query.setHousesId(houseId);
        query.setState(RentStateCons.VALID);
        rentMapper.select(query);
        return rentMapper.select(query);
    }

    /**
     * 上位保存服务派工
     * @param serviceDelivery
     * @return
     */
    public CommonResponse serviceDelivery(ServiceDelivery serviceDelivery,Employee employee)throws Exception {
        Tenant tenant = tenantMapper.selectByPrimaryKey(serviceDelivery.getTenantId());
        Houses houses = housesMapper.selectByPrimaryKey(serviceDelivery.getHouseId());
        Community community = communityMapper.selectByPrimaryKey(houses.getCommunityId());
        Bus bus = new Bus();
        bus.setBusType(serviceDelivery.getBusType());
        bus.setTenantId(tenant.getId());
        bus.setTenantName(tenant.getName());
        bus.setTenantTel(tenant.getPhone());
        bus.setDes(serviceDelivery.getBusdeis());
        bus.setCommunity(community.getCommunity());
        bus.setHouses(houses.getHouseNumb());
        bus.setInsTime(new Date());
        bus.setHousesId(houses.getId());
        bus.setState(BusStateCons.APPLY);
        bus.setDelState(StatusCons.VALID);
        bus.setEmployeeId(employee.getId());
        if (serviceDelivery.getWaiterId() != null) {
            Waiter waiter = witerMapper.selectByPrimaryKey(serviceDelivery.getWaiterId());
            setWaiter(waiter, bus);
        }
        busMapper.insertSelective(bus);
        return CommonResponse.buildUpdateSuccessResponse("派工成功!",null);
    }

    private void setWaiter(Waiter waiter, Bus bus) {
        bus.setWaiter(waiter.getId());
        bus.setWaiterName(waiter.getName());
        bus.setWaiterTel(waiter.getPhone());
        bus.setWaiterTime(new Date());
        // 1正常 2 超时2小时 3超时4小时 4超时8小时
        bus.setWarningState(1);
        bus.setState(BusStateCons.ORDER);
    }

    /**
     * 获取服务列表
     * @param request
     * @return
     */
    public PageResponse<List<Bus>> queryBusList(PageRequest<Bus> request) {
        PageUtil.start(request);
        return PageUtil.getPageResponse(busMapper.getBusList(request.getQuery()));
    }

    /**
     * 派工/重新派工
     * @param dispatch
     * @return
     */
    public CommonResponse dispatch(Dispatch dispatch)throws Exception {
        Waiter waiter = witerMapper.selectByPrimaryKey(dispatch.getWaiterId());
        Bus bus = new Bus();
        bus.setId(dispatch.getBusId());
        bus.setWaiterdes(dispatch.getWaiterdes());
        setWaiter(waiter, bus);
        busMapper.updateByPrimaryKeySelective(bus);
        return CommonResponse.buildUpdateSuccessResponse("派工成功!",null);
    }

    /**
     * 服务完成
     * @param completeBean
     * @return
     */
    @Override
    public CommonResponse complete(CompleteBean completeBean) {
        Bus bus = new Bus();
        bus.setId(completeBean.getBusId());
        bus.setResult(completeBean.getResult());
        bus.setResultTime(completeBean.getResultTime());
        bus.setState(BusStateCons.COMPLETE);
        bus.setWarningState(1); // 1正常 2 超时2小时 3超时4小时 4超时8小时
        busMapper.updateByPrimaryKeySelective(bus);
        return CommonResponse.buildUpdateSuccessResponse("提交成功!",null);
    }
}
